package com.fingard.dsp.bankset;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.DSPCenter;
import com.fingard.dsp.DSPSet;
import com.fingard.dsp.bank.directbank.fngrd01.FnGrd01Base;
import com.fingard.dsp.bank.reqrespobj.ReqRespHeader;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.FGBiz;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MappingCode {

    public String urid;
    public String directPayWay;
    public String packetType;
    public String directAccessCode;
    public String payCode;
    public String payInfoCode;
    public String payInfo;

    public String readExcel(String filepath) throws Exception {
        try {
            Workbook wb = new HSSFWorkbook(new FileInputStream(filepath));
            Sheet sheet = wb.getSheetAt(0);

            Row totalRow = sheet.getRow(5);
            String totalNum = getCellValue(totalRow.getCell(1));

            StringBuilder sbFileContent = new StringBuilder();
            for (int i = 9; i < 9 + Integer.parseInt(totalNum); i++) {
                Row detailRow = sheet.getRow(i);
                if (detailRow == null) {// 略过空行
                    continue;
                }
                int cellSize = detailRow.getLastCellNum();
                StringBuilder eachline = new StringBuilder();
                for (int k = 0; k < cellSize; k++) {
                    Cell cell = detailRow.getCell(k);
                    if (eachline.length() > 0) {
                        eachline.append(",");
                    }
                    eachline.append(getCellValue(cell));
                }
                sbFileContent.append(eachline).append("\r\r\n");
            }
            return sbFileContent.toString();
        } catch (FileNotFoundException e) {
            throw e;
        }
    }

    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }

        //把数字当成String来读，避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                Date theDate = cell.getDateCellValue();
                SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cellValue = dff.format(theDate);
            } else {
                cell.setCellType(Cell.CELL_TYPE_STRING);
            }
        }

        //判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //数字
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date theDate = cell.getDateCellValue();
                    SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    cellValue = dff.format(theDate);
                } else {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    public Map readTransStateByMappingCode(ReqRespHeader tmpHeader) throws Exception {
//        String localFilePath = "D:" + File.separator + "data" + File.separator + tmpHeader.bankCode + ".xls";
//        String localFilePath = "D:" + File.separator + "data" + File.separator + tmpHeader.bankCode + ".csv";
        //通过配置文件的方式设置文件路径 --范天星 2020/01/09
        String localFilePath = FGBiz.dspCenter.dspSet.simulataFilePath + tmpHeader.bankCode + ".csv";
        File file = new File(localFilePath);
        Map<String, Object> mapping = new HashMap<String, Object>();
        if (file.exists()) {
            String fileContent = FileHelper.readFileText(localFilePath, "utf-8");
            if (StringHelper.hasAnyChar(fileContent)) {
                fileContent = fileContent.replace("\"", "");
                String[] totalLine = fileContent.split("\r\n");
                for (String eachline : totalLine) {
                    MappingCode mappingCode = new MappingCode();
                    String[] eachNode = eachline.split(",");
                    mappingCode.urid = eachNode[0];
                    mappingCode.directPayWay = eachNode[1];
                    mappingCode.packetType = eachNode[2];
                    mappingCode.directAccessCode = eachNode[3];
                    mappingCode.payCode = eachNode[4];
                    mappingCode.payInfoCode = eachNode[5];
                    mappingCode.payInfo = eachNode[6];
                    mapping.put(mappingCode.urid, mappingCode);
                }
            } else {
                System.out.println("映射码表为空");
            }
        }
        return mapping;
    }

    public void writeFile(String localFilePath, Map mapQuery) {
        try {
            RandomAccessFile randomFile = null;
            randomFile = new RandomAccessFile(localFilePath, "rw");
            // 文件长度，字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.write((mapQuery.toString() + "\r\n").getBytes("GBK"));
            randomFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map readQyerys(String localFilePath) throws Exception {
        String tmpStrRet = FileHelper.readFileText(localFilePath, "GBK");
        if (StringHelper.hasAnyChar(tmpStrRet)) {

            String[] eachlines = tmpStrRet.split("\r\n");
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < eachlines.length; i++) {
                String s = eachlines[i];
                if (StringHelper.hasAnyChar(s)) {
                    s = s.substring(1, s.length() - 1);
                    String key = s.substring(0, s.indexOf("="));
                    String value = s.substring(s.indexOf("=") + 1, s.length());
                    JSONObject query = JSONObject.parseObject(value);
                    map.put(key, query);
                }
            }
            return map;
        } else {
            return null;
        }
    }
}
